<?php
/**
 * +--------------------------------------------------------+
 * @Created by PhpStorm.
 * @Category BaseService.php
 * @Depiction:
 * Author: hwy
 * Date: 2021/2/2  15:34
 * +--------------------------------------------------------+
 */

namespace App\Services;

use App\Exceptions\ResponseException;
use Illuminate\Support\Facades\DB;

/**
 * Class BaseService
 * @package App\Services
 * @Depiction
 * @Author hwy
 * @Date  2021/2/3  11:00
 */
class BaseService
{
    protected $perPage = 10;

    const STATUS_ON = 1;
    const STATUS_OFF = 2;

    /**
     * 保存类实例的私有静态成员变量
     * 此处有问题：在homestead中，私有属性继承出错，修改为protected。其他环境（phpstudy,lnmp一键）没问题
     * @var $instance
     */
    protected static $instance;

    protected static $_model;

    /**
     * @return static
     * @Depiction 对外提供获取唯一实例的方法
     * @Author hwy
     * @Date  2021/2/3  11:16
     */
    public static function getInstance()
    {
        //检测是否被实例化
        if (static::$instance instanceof static) {
            return static::$instance;
        }
        static::$instance = new static();
        return static::$instance;
    }

    /**
     * BaseService constructor.
     * 定义一个私有的构造函数，确保单例类不能通过new关键字实例化，只能被其自身实例化
     */
    private function __construct()
    {
    }

    /**
     * @Depiction 定义私有的__clone()方法，确保单例类不能被复制或克隆
     * @Author hwy
     * @Date  2021/2/3  11:18
     */
    private function __clone()
    {
    }

    public function commonCreate($add_data)
    {
        try {
            $add = $this->setting_config_tab->create($add_data);
        } catch (\Exception $e) {
            return return_error_msg($e->getMessage());
        }

        return $add;
    }

    public function commomDel($query, $ids)
    {
        if(is_string($ids)){
            $ids = [$ids];
        }
        $data = $query->query()->whereIn('id',$ids)->get();
        if (empty($data)) {
            return return_error_msg(ResponseException::DATA_NOT_EXIST_MESSAGE);
        }
        DB::beginTransaction();
        foreach ($data as $value){
            try {
                $del = $value->delete();
            } catch (\Exception $e) {
                DB::rollBack();
                return return_error_msg($e->getMessage());
            }
        }
        if ($del) {
            DB::commit();
            return return_success_msg(ResponseException::SUCCESS_DELETE_MESSAGE);
        } else {
            return return_error_msg(ResponseException::ERROR_DELETE_MESSAGE);
        }

    }

    /**
     * @param $params
     * @param $query
     * @return mixed
     * @Depiction 获取列表时，请求的通用参数，统一组合
     * @Author hwy
     * @Date  2021/2/3  11:14
     */
    public function paramsSet($params, $query)
    {
        if (!empty($params['field']) && !empty($params['order'])) {
            $query = $query->orderBy($params['field'], $params['order']);
        }
        if (!empty($params['name'])) {
            $query = $query->where('name', 'like', '%' . $params['name'] . '%');
        }

        return $query;
    }

    public function updateBatch($multipleData = [], $tableName)
    {
        try {
            if (empty($multipleData)) {
                throw new \Exception("数据不能为空");
            }

            $firstRow     = current($multipleData);
            $updateColumn = array_keys($firstRow);
            // 默认以id为条件更新，如果没有ID则以第一个字段为条件
            $referenceColumn = isset($firstRow['id']) ? 'id' : current($updateColumn);
            unset($updateColumn[0]);

            // 拼接sql语句
            $updateSql = "UPDATE " . $tableName . " SET ";
            $sets      = [];
            $bindings  = [];

            foreach ( $updateColumn as $uColumn ) {
                $setSql = "`" . $uColumn . "` = CASE ";
                foreach ( $multipleData as $data ) {
                    $setSql     .= "WHEN `" . $referenceColumn . "` = ? THEN ? ";
                    $bindings[] = $data[$referenceColumn];
                    $bindings[] = $data[$uColumn];
                }
                $setSql .= "ELSE `" . $uColumn . "` END ";
                $sets[] = $setSql;
            }

            $updateSql .= implode(', ', $sets);
            $whereIn   = collect($multipleData)->pluck($referenceColumn)->values()->all();
            $bindings  = array_merge($bindings, $whereIn);
            $whereIn   = rtrim(str_repeat('?,', count($whereIn)), ',');
            $updateSql = rtrim($updateSql, ", ") . " WHERE `" . $referenceColumn . "` IN (" . $whereIn . ")";
            // 传入预处理sql语句和对应绑定数据
            return DB::update($updateSql, $bindings);
        } catch (\Exception $e) {
//            dd($e);
            return false;
        }
    }

    /**
     * @param $params
     * @return int
     * @Depiction 每页数量
     * @Author hwy
     * @Date  2021/2/3  11:18
     */
    public function perPage($params)
    {
        return $perPage = empty($params['perPage']) ? $this->perPage : $params['perPage'];
    }

    /**
     * @param $param
     * @return int|mixed
     * @Depiction 设置开关值
     * @Author hwy
     * @Date 2021/5/27  10:57
     */
    public function commonSetStatusValue($param)
    {
        $status = empty($param) ? self::STATUS_OFF : $param;
        return $status;
    }

}
